#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include "getabsmod.h"
//#define DEBUG
void push(char *str,struct stack **top) {
	struct stack *tp;
	
	#ifdef DEBUG
	printf("Pushing %s ",str);
	#endif
	tp = (struct stack*) malloc(sizeof(struct stack));
	if (!tp) {
		fprintf(stderr,"Stack Overflow");
		exit(-1);
	}
	
#ifdef DEBUG
	printf("\t\tPrevious Top : ");
	if (*top==NULL) 
		printf(" NULL ");
	else
		printf(" %s ",(*top)->data);
#endif
	tp->data=strdup(str);
	tp->next=*top;
	*top=tp;
#ifdef DEBUG
	printf("\t Current top : %s \n",(*top)->data);
#endif

}
char* pop(struct stack **top) {
#ifdef DEBUG
	printf("Previous Top : ");
	if (*top==NULL) 
		printf(" NULL ");
	else
		printf(" %s ",(*top)->data);
#endif
	if (top==NULL) { 
		fprintf(stderr,"Stack Underflow");
		exit(-1);
	}
 	char *tmp;
	struct stack *curtop;
	tmp=(*top)->data;
	curtop=*top;
	*top=(*top)->next;
	free(curtop);
#ifdef DEBUG
	printf("\t\tCurrent Top : ");
	if (*top==NULL) 
		printf(" NULL ");
	else
		printf(" %s ",(*top)->data);
	printf("\t\tPopping %s \n",tmp);
#endif
	return tmp;
}
char* getabsmod(char *rel) {
	char *abs;
	char *copy;
	int depth;

	#ifdef DEBUG
	printf("Relative Path : %s\n",rel);
	#endif

	// Delimiters
        const char delim[] = "/";
	
	char *token,*temp;
	
	struct stack *top;
	top=NULL;
	depth=0;
	// Process the relative link
	copy=strdup(rel);
	token=strtok(copy,delim);
 	while (token!=NULL) {
		#ifdef DEBUG
		printf("Token : %s \n",token);
		#endif
		// Go up one by one level
		if (strcmp(token,"..")==0) {
		        if (depth==0)
				return NULL;
			temp=pop(&top);
			if (temp!=NULL)
				free(temp);
			depth--;
		}
		// Do nothing stay in current level
		else if (strcmp(token,".")==0) {}
		else {
			push(token,&top);
			depth++;
		}
		token=strtok(NULL,delim);
	}
	free(copy);
	int length=0,i=0;

	char **paths;
        paths=(char**)malloc(depth*sizeof(char*));	
	while (top!=NULL){
		temp=pop(&top);
		paths[i]=strdup(temp);
		free(temp);
#ifdef DEBUG
		printf("length = %d | paths[%d] = %s \n",length,i,temp);
#endif
		length+=strlen(paths[i])+1;
		i++;
	}

#ifdef DEBUG
		printf("Popped all datas. Forming the absolute path\n i = %d\n",i);
#endif
	abs=(char*)malloc(length+2);
	strcpy(abs,"/");
 	while (i>0) {
		i--;
		strcat(abs,paths[i]);		
		strcat(abs,"/");
	}
	for(i=0;i<depth;i++)
		free(paths[i]);
	free(paths);
	abs[strlen(abs)-1]='\0'; // Remove the trailing /
	return(abs);
}

